<?php
/**
 * Created by IntelliJ IDEA.
 * User: huyu
 * Date: 16/8/28
 * Time: 上午10:20
 */
namespace app\controllers;
use yii\web\Controller;

require_once('vendor/upyun.class.php');
//require_once('vendor/Uploader.class.php');
include_once('vendor/Uploader.class.php');
use app\models\User;
use app\models\Commodity;
use app\models\Postage_template;
use app\models\Postage_template_detail;



class PostageTemplateController extends Controller{
    public function init(){
        $this->enableCsrfValidation = false;
        if(!\Yii::$app->user->id){
            $url = \Yii::$app->request->getPathInfo();
            return $this->redirect('../login/index?url='.$url);
        }
        $userId = \Yii::$app->user->id;
        $user = new User();
        $admin = $user->findIdentity($userId);
        if($admin['type']==1 or $admin['type']==0){
            return $this->redirect('../login/logout');
        }
    }

    public function actionIndex(){
        $view = \Yii::$app->view;
        $view->params['menuitemid']=25;
        return $this->render('index');
    }

    public function actionGetAll()
    {
        $postageTemplateModel = new Postage_template();
        $rs = $postageTemplateModel->getAll();
        echo json_encode($rs);
    }

    public function actionAdd()
    {
        $request = \Yii::$app->request;
        $name = $request->post('name');

        $model = new Postage_template();
        $model->name=$name;
        $model->default_unit_price=0.00;
        if($model->save() > 0){
            $model->id=\Yii::$app->db->getLastInsertID();
            echo json_encode([
                "id" => $model->id,
                "name" => $model->name,
                "default_unit_price" => $model->default_unit_price,
            ]);
        } else{
            echo json_encode('0');
        }
    }

    public function actionDelete()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        if (Commodity::find()->where(['postage_template_id'=>$id])->exists()) {
            echo json_encode(["status"=>"failed", "message"=>"不能删除正在使用的运费模板!"]);
        }
        else {
            Postage_template::updateAll(['del_flag'=>'0'],['id'=>$id]);
            echo json_encode(["status"=>"success"]);
        }
    }

    public function actionEdit()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $insertData = $request->post('insertData');
        $deleteData = $request->post('deleteData');
        if ($insertData == null && $deleteData == null) {
            echo json_encode(["status"=>"succeed", "message"=>"没有更新"]);
            return;
        }
        $templateDetails = [];
        $templateDetailsToDelete = [];
        $defaultUnitPrice = 0.00;
        $isDefaultUnitPriceSet = false;
        if ($insertData != null) {
            foreach ($insertData as $item) {
                if ($item["province_name"] == "全国") {
                    $isDefaultUnitPriceSet = true;
                    $defaultUnitPrice = $item["unit_price"];
                } else {
                    $templateDetail = Postage_template_detail::find()->where(['postage_template_id'=>$id,
                        "province_name"=>$item["province_name"]])->one();
                    if ($templateDetail == null) {
                        $templateDetail = new Postage_template_detail();
                    }
                    $templateDetail->postage_template_id = $id;
                    $templateDetail->province_name = $item["province_name"];
                    $templateDetail->unit_price = $item["unit_price"];
                    array_push($templateDetails, $templateDetail);
                }
            }
        }
        if ($deleteData != null) {
            foreach ($deleteData as $item) {
                if ($item["province_name"] == "全国") {
                    $isDefaultUnitPriceSet = true;
                    $defaultUnitPrice = 0.00;
                } else {
                    $templateDetail = Postage_template_detail::find()->where(['postage_template_id'=>$id,
                        "province_name"=>$item["province_name"]])->one();
                    array_push($templateDetailsToDelete, $templateDetail);
                }
            }
        }
        $model = new Postage_template();
        $connection=\Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try {
            if ($isDefaultUnitPriceSet) {
                $template = Postage_template::find()->where(['id'=>$id])->one();
                $template->default_unit_price = $defaultUnitPrice;
                $template->update();
            }
            foreach ($templateDetailsToDelete as $templateDetail) {
                $templateDetail->delete();
            }
            foreach ($templateDetails as $templateDetail) {
                $templateDetail->save();
            }
            $data = (new Postage_template())->getDetails($id);
            if (!$this->validateTemplateDetails($data)){
                echo json_encode(["status"=>"failed", "message"=>"填写信息有误,请检查"]);
                $transaction->rollBack();
            }
            else {
                echo json_encode(["status" => "succeed", "message" => "succeed"]);
                $transaction->commit();
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            echo json_encode(["status"=>"failed", "message"=>$e.getMessage()]);
        }
        return;
    }

    private function validateTemplateDetails($data) {
        $provinces = [];
        if ($data != null) {
            foreach ($data as $item) {
                foreach(explode(', ', $item["province_name"]) as $province) {
                    if (array_search($province, $provinces)) {
                        return false;
                    }
                    else {
                        array_push($provinces, $province);
                    }
                }
            }
        }
        return true;
    }

    public function actionGetDetail()
    {
        $request = \Yii::$app->request;
        $template_id = $request->post('template_id');
        $model=Postage_template_detail::find()->where(['postage_template_id'=>$template_id])->all();
        $rows = [];
        foreach ($model as $item) {
            array_push($rows, ["province_name"=>$item->province_name, "unit_price"=>number_format($item->unit_price,2)]);
        }
        echo json_encode([
            "total" => count($model),
            "rows"=>$rows]);
    }

    public function actionGetAllProvince(){
        $result=\Yii::$app->db->createCommand('SELECT name FROM hcps_province')->queryAll();
        echo json_encode($result);
    }
}